package org.eiahe.hr.employeeRelation.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ehe.common.core.domain.dto.StartProcessDTO;
import org.ehe.common.core.domain.dto.StartProcessReturnDTO;
import org.ehe.common.core.service.WorkflowService;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.erp.enums.ErpAuditStatus;
import org.ehe.system.domain.HrEmployee;
import org.ehe.system.mapper.HrEmployeeMapper;
import org.eiahe.hr.employeeRelation.domain.ContractTerminationApplication;
import org.eiahe.hr.employeeRelation.domain.RewardPunishmentRecord;
import org.eiahe.hr.employeeRelation.domain.bo.ContractTerminationApplicationBo;
import org.eiahe.hr.employeeRelation.domain.bo.RewardPunishmentRecordBo;
import org.eiahe.hr.employeeRelation.domain.vo.ContractTerminationApplicationVo;
import org.eiahe.hr.employeeRelation.mapper.ContractTerminationApplicationMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.eiahe.hr.employeeRelation.service.IContractTerminationService;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 合同终止服务实现类
 *
 * @author zhangnn
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ContractTerminationServiceImpl implements IContractTerminationService {

    private final ContractTerminationApplicationMapper applicationMapper;
    private final WorkflowService workflowService;
    private final HrEmployeeMapper employeeMapper;

    /**
     * 查询合同终止申请列表
     *
     * @param bo 合同终止申请业务对象
     * @return 合同终止申请列表
     */
    @Override
    public List<ContractTerminationApplicationVo> selectContractTerminationApplicationList(
            ContractTerminationApplicationBo bo) {
        LambdaQueryWrapper<ContractTerminationApplication> wrapper = Wrappers.lambdaQuery();
        // 根据需要添加查询条件
        return applicationMapper.selectVoList(wrapper);
    }

    /**
     * 查询合同终止申请列表(分页)
     *
     * @param bo        合同终止申请业务对象
     * @param pageQuery 分页参数
     * @return 合同终止申请分页列表
     */
    @Override
    public TableDataInfo<ContractTerminationApplicationVo> selectContractTerminationApplicationList(
            ContractTerminationApplicationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ContractTerminationApplication> lqw = buildQueryWrapper(bo);
        // 根据需要添加查询条件
        IPage<ContractTerminationApplicationVo> page = applicationMapper.selectVoPage(pageQuery.build(), lqw);
        page.getRecords().forEach(p ->{
            Long employeeId = p.getEmployeeId();
            HrEmployee hrEmployee = employeeMapper.selectById(employeeId);
            if(Objects.nonNull(hrEmployee)){
                p.setEmployeeName(hrEmployee.getEmployeeName());
            }
        });
        return TableDataInfo.build(page);
    }

    private LambdaQueryWrapper<ContractTerminationApplication> buildQueryWrapper(ContractTerminationApplicationBo bo) {
        LambdaQueryWrapper<ContractTerminationApplication> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(bo.getEmployeeName())) {
            List<HrEmployee> employees = employeeMapper.selectList(
                Wrappers.lambdaQuery(HrEmployee.class)
                    .like(HrEmployee::getEmployeeName, bo.getEmployeeName()));
            List<String> employeeNos = Optional.ofNullable(employees)
                .orElse(Collections.emptyList())
                .stream()
                .map(HrEmployee::getEmployeeNo)
                .collect(Collectors.toList());

            if (CollUtil.isEmpty(employeeNos)) {
                lqw.eq(ContractTerminationApplication::getEmployeeNo, -1);
            } else {
                lqw.in(ContractTerminationApplication::getEmployeeNo, employeeNos);
            }
        }
        lqw.eq(StringUtils.isNotBlank(bo.getEmployeeNo()), ContractTerminationApplication::getEmployeeNo, bo.getEmployeeNo());
        lqw.eq(StringUtils.isNotBlank(bo.getTerminationType()), ContractTerminationApplication::getTerminationType,
            bo.getTerminationType());
        return lqw;
    }
    /**
     * 通过申请ID查询合同终止申请信息
     *
     * @param applicationId 申请ID
     * @return 合同终止申请信息
     */
    @Override
    public ContractTerminationApplicationVo selectContractTerminationApplicationById(Long applicationId) {
        return applicationMapper.selectVoById(applicationId);
    }

    /**
     * 新增合同终止申请
     *
     * @param bo 合同终止申请业务对象
     * @return 结果
     */
    @Override
    public Boolean insertContractTerminationApplication(ContractTerminationApplicationBo bo) {
        ContractTerminationApplication application = MapstructUtils.convert(bo, ContractTerminationApplication.class);
        // 发起申请
        if (applicationMapper.insert(application) > 0) {
            // 发起工作流程
            if (bo.getApprovalStatus().equals(ErpAuditStatus.SUBMITTED.getStatus().toString())) {
                StartProcessDTO process = new StartProcessDTO();
                Map<String, Object> map = new HashMap<>();
                map.put("type", "contractTermination");
                process.setVariables(map);
                process.setFlowCode("contractTermination");
                process.setBusinessId(String.valueOf(application.getApplicationId()));
                StartProcessReturnDTO processReturnDTO = workflowService.startWorkFlow(process);
                log.info("流程审批发起成功，已启动: 合同终止={}, 员工编号={}", application.getApplicationId(), application.getEmployeeNo());

                // 自己提交的流程节点默认审批完成
                String employeeName = "";
                HrEmployee hrEmployee = employeeMapper.selectById(bo.getEmployeeId());
                if (Objects.nonNull(hrEmployee)) {
                    employeeName = hrEmployee.getEmployeeName();
                }
                Long taskId = processReturnDTO.getTaskId();
                workflowService.completeTask(taskId,
                        "员工:" + employeeName +
                                "编号:【" + application.getEmployeeNo() + "】" +
                                "终止劳动合同。原因:" + bo.getTerminationReason());
            }
        }
        return true;
    }

    /**
     * 修改合同终止申请
     *
     * @param bo 合同终止申请业务对象
     * @return 结果
     */
    @Override
    public Boolean updateContractTerminationApplication(ContractTerminationApplicationBo bo) {
        ContractTerminationApplication application = MapstructUtils.convert(bo, ContractTerminationApplication.class);
        return applicationMapper.updateById(application) > 0;
    }

    /**
     * 批量删除合同终止申请
     *
     * @param applicationIds 需要删除的申请ID数组
     * @return 结果
     */
    @Override
    public Boolean deleteContractTerminationApplicationByIds(Long[] applicationIds) {
        return applicationMapper.deleteBatchIds(Arrays.asList(applicationIds)) > 0;
    }

    /**
     * 审批通过
     * @param bo
     * @return
     */
    @Override
    public Boolean approveContractTermination(ContractTerminationApplicationBo bo) {
        ContractTerminationApplication terminationApplication = this.applicationMapper.selectById(bo.getApplicationId());
        terminationApplication.setApprovalStatus("1"); //通过
        terminationApplication.setProcessingResult(bo.getProcessingResult());
        applicationMapper.updateById(terminationApplication);
        return true;
    }

    /**
     * 审批拒绝
     * @param bo
     * @return
     */
    @Override
    public Boolean rejectContractTermination(ContractTerminationApplicationBo bo) {
        ContractTerminationApplication terminationApplication = this.applicationMapper.selectById(bo.getApplicationId());
        terminationApplication.setApprovalStatus("2"); //驳回
        terminationApplication.setProcessingResult(bo.getProcessingResult());
        applicationMapper.updateById(terminationApplication);
        return true;
    }
}
